package com.voicechat.firstmet.activity;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.voicechat.firstmet.R;
import com.voicechat.firstmet.base.BaseActivity;
import com.voicechat.firstmet.bean.MySelfInfoBean;
import com.voicechat.firstmet.imcontrol.ILoginView;
import com.voicechat.firstmet.imcontrol.LoginHelper;
import com.voicechat.firstmet.net.HTTPAPI;
import com.voicechat.firstmet.net.service.LoginService;
import com.voicechat.firstmet.utils.MD5Utils;
import com.voicechat.firstmet.utils.ParcelableUtils;
import com.voicechat.firstmet.utils.PhoneUtils;
import com.voicechat.firstmet.utils.SPUtils;
import com.voicechat.firstmet.utils.StatusBarUtils;
import com.voicechat.firstmet.utils.Utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @ProjectName: FirstMet
 * @Package: com.voicechat.firstmet.activity_imessage
 * @ClassName: SetPassWordActivity
 * @Description: 设置密码页面
 * @Author: ljp
 * @CreateDate: 2018/8/31 9:16
 * @Version: 1.0
 */
public class SetPassWordActivity extends BaseActivity implements View.OnClickListener , ILoginView {
    @BindView(R.id.tv_text_set)
    TextView tvTextSet;
    @BindView(R.id.et_pass_word)
    EditText etPassWord;
    @BindView(R.id.image_open)
    Button imageOpen;
    @BindView(R.id.tv_text_sure)
    TextView tvTextSure;
    @BindView(R.id.et_pass_word_sure)
    EditText etPassWordSure;
    @BindView(R.id.image_open2)
    Button imageOpen2;
    @BindView(R.id.tv_sure)
    TextView tvSure;
    @BindView(R.id.iv_back)
    LinearLayout ivBack;
    private String mobile;
    private LoginHelper loginHelper ;
    private String flag;//0为注册设置新密码，1为用户修改密码

    private boolean selected = false;
    private boolean selected2 = false;

    private boolean passTrue = false;
    private boolean passTrue2 = false;

    private String TAG = "SetPassWordActivity";
    private String id;

    @Override
    protected int setStatusBarColor() {
        return 0;
    }

    @Override
    protected boolean isSettingStatusBarText() {
        return false;
    }

    @Override
    protected int loadLayout() {
        return R.layout.activity_set_password;
    }

    @Override
    protected void initLayout(Bundle savedInstanceState) {
        mobile = getIntent().getStringExtra("mobile");
        flag = getIntent().getStringExtra("flag");
        ButterKnife.bind(this);
        //透明状态栏
        StatusBarUtils.Full(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            this.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
        initView();


    }

    private void initView() {
        if(flag.equals("1")){
            tvTextSet.setText("设置新密码");
            tvTextSure.setText("确认新密码");
        }
        imageOpen.setOnClickListener(this);
        imageOpen2.setOnClickListener(this);
        tvSure.setOnClickListener(this);
        ivBack.setOnClickListener(this);
        tvSure.setClickable(false);
        etPassWord.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String trim = s.toString().trim();
                if (!TextUtils.isEmpty(trim)) {
                    imageOpen.setVisibility(View.VISIBLE);
                } else {
                    imageOpen.setVisibility(View.GONE);
                }
                if(trim.length() >= 6){
                    passTrue = true;
                    if(passTrue2){
                        tvSure.setClickable(true);
                        tvSure.setBackgroundResource(R.drawable.login_btn);
                    }else {
                        tvSure.setClickable(false);
                        tvSure.setBackgroundResource(R.drawable.login_btn_d5d5d5);
                    }
                }else {
                    passTrue = false;
                    tvSure.setClickable(false);
                    tvSure.setBackgroundResource(R.drawable.login_btn_d5d5d5);
                }
            }
            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        etPassWordSure.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String trim = s.toString().trim();
                if (!TextUtils.isEmpty(trim)) {
                    imageOpen2.setVisibility(View.VISIBLE);
                } else {
                    imageOpen2.setVisibility(View.GONE);
                }
                if(trim.length() >= 6){
                    passTrue2 = true;
                    if(passTrue){
                        tvSure.setClickable(true);
                        tvSure.setBackgroundResource(R.drawable.login_btn);
                    }else {
                        tvSure.setClickable(false);
                        tvSure.setBackgroundResource(R.drawable.login_btn_d5d5d5);
                    }
                }else {
                    passTrue2 = false;
                    tvSure.setClickable(false);
                    tvSure.setBackgroundResource(R.drawable.login_btn_d5d5d5);
                }
            }
            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        //限制密码不能输入中文
        Utils.setEdNoChinaese(etPassWord);
        Utils.setEdNoChinaese(etPassWordSure);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //确定按钮
            case R.id.tv_sure:
                setPasswore();
                break;
            //眼睛打开关闭
            case R.id.image_open:
                if (selected) {
                    imageOpen.setSelected(true);
                    selected = false;
                    // etPassWord.setInputType(InputType.TYPE_CLASS_TEXT);
                    etPassWord.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    etPassWord.setSelection(etPassWord.getText().toString().length());
                } else {
                    imageOpen.setSelected(false);
                    selected = true;
                    //etPassWord.setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    etPassWord.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    etPassWord.setSelection(etPassWord.getText().toString().length());
                }
                break;
            case R.id.image_open2:
                if (selected2) {
                    imageOpen2.setSelected(true);
                    selected2 = false;
                    // etPassWord.setInputType(InputType.TYPE_CLASS_TEXT);
                    etPassWordSure.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    etPassWordSure.setSelection(etPassWordSure.getText().toString().length());
                } else {
                    imageOpen2.setSelected(false);
                    selected2 = true;
                    //etPassWord.setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    etPassWordSure.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    etPassWordSure.setSelection(etPassWordSure.getText().toString().length());
                }
                break;
            case R.id.iv_back:
                finish();
                break;
        }
    }
    /**
     * 确定按钮
     */
    private void setPasswore() {
        String passWord = etPassWord.getText().toString().trim();
        String passWord2 = etPassWordSure.getText().toString().trim();
        String judge = "^[0-9]{1,}+$";
        Pattern p = Pattern.compile(judge);
        Matcher m = p.matcher(passWord);
        if(p.matcher(passWord.substring(0,1)).matches()){
            toast_MakeText("密码以字母开头,请重新输入!");
            return;
        }
        if (m.matches() ){
            toast_MakeText("密码不能为纯数字,请重新输入!");
            return;
        }
        if (Utils.isChar(passWord)) {
            toast_MakeText("密码不能为纯字母,请重新输入!");
            return;
        }
        if (!(passWord.length() >= 6 && passWord.length() <= 16)) {
            toast_MakeText("密码长度为6-16位字符!");
            return;
        }
        /*if(TextUtils.isEmpty(passWord) || TextUtils.isEmpty(passWord2) ){
            toast_MakeText("请输入密码");
            return;
        }*/
        String confirmpassword = etPassWordSure.getText().toString().replace(" ", "");
        if (TextUtils.isEmpty(confirmpassword) || TextUtils.equals(confirmpassword, "")) {
            toast_MakeText("请再次输入密码!");
            return;
        }
        if (!TextUtils.equals(passWord, confirmpassword)) {
            toast_MakeText("两次密码不一致,请重新输入!");
            return;
        }
        String md5PassWord = MD5Utils.getMd5Value(passWord);
        Log.i(TAG, "setPasswore: ------"+md5PassWord);
        //网络请求  判断flag  0注册用户设置密码，1用户更改密码
        String deviceInfo = PhoneUtils.getDeviceInfo(context);
        String channel = Utils.getChannel(context);
        if(flag.equals("0")){
            LoginService.registerPassword(mobile,md5PassWord,deviceInfo,channel).subscribe(mySelfInfoBean -> {
                Log.i(TAG, "setPasswore: ------"+mySelfInfoBean.toString());
                if(mySelfInfoBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS){
                    loginHelper = new LoginHelper(this);
                    MySelfInfoBean.ObjectBean object = mySelfInfoBean.getObject();
                    id = object.getId();
                    SPUtils.setEditorKeyValue(SPUtils.SP_PHONE,mobile);
                    SPUtils.setEditorKeyValue(SPUtils.SP_TOKEN,object.getToken());
                    SPUtils.setEditorKeyValue(SPUtils.SP_USERSIG,mySelfInfoBean.getMap().getUserSig());
                    SPUtils.setEditorKeyValue(SPUtils.SP_MYSELFINFO, ParcelableUtils.marshall(object));
                    loginHelper.login(object.getId(),mySelfInfoBean.getMap().getUserSig());
                }else if(mySelfInfoBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_FAIL){
                    toast_MakeText(mySelfInfoBean.getMsg());
                }
            },throwable -> {
                Log.i(TAG, "setPasswore: ----"+throwable.toString());
            });
        }else if(flag.equals("1")) {
            LoginService.forgetPassword(mobile,md5PassWord,deviceInfo,"").subscribe(result -> {
                Log.i(TAG, "setPasswore: ------"+result.toString());
                if(result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS){
                    Intent intent = new Intent(this, LoginPassWordActivity.class);
                    intent.putExtra("mobile",mobile);
                    startActivity(intent);
                }
            },throwable -> {
               // Log.i(TAG, "setPasswore: ----"+throwable.toString());
            });
        }
    }


    @Override
    public void updateLoginState(boolean state) {
    }
    @Override
    public void onLoginSDKSuccess() {
        Intent intent = new Intent(this, RegisterActivity.class);
        intent.putExtra("mobile",mobile);
        startActivity(intent);
        finish();
    }
    @Override
    public void onLoginSDKFailed(int errCode, String errMsg) {
        //loginHelper.login(id,SPUtils.getEditoString(SPUtils.SP_USERSIG));
    }
    @Override
    public void onLogoutSDKSuccess() {
    }
    @Override
    public void onLogoutSDKFailed(int errCode, String errMsg) {
    }
}
